import { _decorator, Component, Button, Node, find, Label, Sprite, SpriteFrame } from 'cc';
const { ccclass, property } = _decorator;

import { Consts } from "../Data/Consts";
import { MaterialData } from "../Config/MaterialData";
import { bdlMgr } from "../Manager/SS_BundleManager";
import TAComponent from "../sdk/TAComponent";
import CommonFunction from "../utils/CommonFunction";
import { SS_AudioManager } from '../Manager/SS_AudioManager';

@ccclass('MaterialPanel')
export default class MaterialPanel extends Component {
    public static Instance: MaterialPanel;
    @property(Button)
    Button_back: Button | null = null;
    @property(Node)
    public content: Node | null = null;

    onLoad() {
        MaterialPanel.Instance = this;

        //        // this.ShowOff();
    }

    ShowOn() {
        this.node.active = true;
        this.AddListener();

        this.Refresh();

        TAComponent.SendEvent(Consts.埋点事件.打开材料界面, {});
    }

    ShowOff() {
        this.node.active = false;
        this.RemoveListener();
    }

    async Refresh() {
        CommonFunction.SetAllChildrenAtive(this.content, false);

        for (let index = 0; index < MaterialData.length; index++) {
            let item_data = MaterialData[index];
            const child = CommonFunction.GetFreeChild(this.content);
            child.active = true;

            let icon: Sprite = find(`bg/frame/icon`, child).getComponent(Sprite);
            let name: Sprite = find(`bg/frame/name`, child).getComponent(Sprite);
            let info: Label = find(`bg/info`, child).getComponent(Label);
            info.string = item_data.dec;

            bdlMgr.getRes<SpriteFrame>(Consts.BundleName.SPRITE, `main/material/icon/${item_data.icon}/spriteFrame`, SpriteFrame).then(res => { icon.spriteFrame = res });
            bdlMgr.getRes<SpriteFrame>(Consts.BundleName.SPRITE, `main/material/name/${item_data.icon}/spriteFrame`, SpriteFrame).then(res => { name.spriteFrame = res });
        }
    }

    AddListener() {
        this.Button_back.node.on("click", this.On_Button_back, this);
    }
    RemoveListener() {
        this.Button_back.node.off("click", this.On_Button_back, this);
    }
    On_Button_back() {
        this.ShowOff();

        SS_AudioManager.PlayButtonAudio();
    }
}